<?php

namespace pmvc\data;

use pmvc\tx\Transaction;
use Exception;

class MysqlTransaction
	implements Transaction {

	private $started 	= FALSE;
	private $committed	= FALSE;
	private $rolledBack	= FALSE;
	private $autoCommit	= FALSE;
	private $dataSource	= NULL;

	public function __construct(MysqlDataSource $dataSource) {
		$this->dataSource = $dataSource;
	}

	public function setAutoCommit($autoCommit) {
		if ($this->started) {
			throw new Exception(
				"Cant set auto commit because transaction is already started");
		}
		$this->autoCommit = ($autoCommit===TRUE || $autoCommit==1);
	}

	public function isAutoCommit() {
		return $this->autoCommit;
	}

	public function isCommited() {
		return $this->committed;
	}

	public function isRolledBack() {
		return $this->rolledBack;
	}

	public function start() {
		if ($this->started) {
			throw new Exception(
				"Cant start transaction because it's already started");
		}
		$this->dataSource->update("set autocommit=".(($this->autoCommit)?"1":"0"));
		$this->dataSource->update("start transaction");
		$this->started = TRUE;
	}

	public function commit() {
		$this->dataSource->update("commit");
		$this->committed = TRUE;
	}

	public function rollback() {
		$this->dataSource->update("rollback");
		$this->rolledBack = TRUE;
	}

}

?>